<?php


namespace App\Services;


use App\Models\Express;

class LogisticsService
{

    public static function logisticsMessage($logisticsName,$logisticsNo,$mobile){
        $msgData = json_encode([
            'language'=>'0',
            'trackingType'=> '1',
            'trackingNumber'=>[$logisticsNo],
            'methodType'=>"1",
            'checkPhoneNo'=>strlen($mobile)>10?substr($mobile,7,4):$mobile
        ]);//读取文件内容
        $requestID = self::create_uuid();
//获取时间戳
        $timestamp = time();

//通过MD5和BASE64生成数字签名
        $msgDigest = base64_encode(md5((urlencode($msgData .$timestamp. config('alipay.other.sfkey') )), TRUE));

        $post_data = array(
            'partnerID' => config('alipay.other.sfid'),
            'requestID' => $requestID,
            'serviceCode' => 'EXP_RECE_SEARCH_ROUTES',
            'timestamp' => $timestamp,
            'msgDigest' => $msgDigest,
            'msgData' => $msgData
        );
//生产环境的地址
        $CALL_URL_PROD = "https://bspgw.sf-express.com/std/service";

        $resultCont = self::send_post($CALL_URL_PROD, $post_data); //沙盒环境

        $express = json_decode($resultCont,true);
//        var_dump($logisticsNo);
//        var_dump($express);
//        var_dump($mobile);
        $data = [];
        $apiResultData=json_decode($express['apiResultData'],true);

        if(isset($express['apiResultCode']) && $express['apiResultCode'] == 'A1000'&& $express['apiResultData']&&$apiResultData['success']){

            if(isset($apiResultData['msgData']['routeResps']['0']['routes'])&&$apiResultData['msgData']['routeResps']['0']['routes']){
                foreach ($apiResultData['msgData']['routeResps']['0']['routes'] as $key=>$value){
                    $data[] = [
                        'time'=>$value['acceptTime'],
                        'opcode'=>$value['opCode'],
                        'context'=>$value['firstStatusName'].'；'.$value['remark'],
                    ];
                }
            }else{
                if($mobile!=5555){
                   return   self::logisticsMessage($logisticsName,$logisticsNo,5555);
                }
//                if($mobile!=4518){
//                    self::logisticsMessage($logisticsName,$logisticsNo,6445);
//                }
            }

            rsort($data);
            return ['data'=>$data];
        }
        return $data;
    }

    public  function send_post($url, $post_data) {

        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded;charset=utf-8',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }


//获取UUID
    public function create_uuid() {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr ( $chars, 0, 8 ) . '-'
            . substr ( $chars, 8, 4 ) . '-'
            . substr ( $chars, 12, 4 ) . '-'
            . substr ( $chars, 16, 4 ) . '-'
            . substr ( $chars, 20, 12 );
        return $uuid ;
    }

}
